package com.example.demo.bizhan.thread;

import lombok.Data;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @description: wait notifyAll必须在synchronized里面调用
 * @time: 2020-10-28 21:27
 * @author: baojinlong
 **/
@Data
public class Person2 {
    private String name;
    private String sex;
    private boolean isEmpty = true;
    // 创建可重入锁对象
    private ReentrantLock reentrantLock = new ReentrantLock();
    private Condition condition = reentrantLock.newCondition();

    // 加synchronized可以解决
    public void set(String name, String sex) {
        reentrantLock.lock();
        try {
            while (!isEmpty) {
                condition.await();
            }
            this.name = name;
            Thread.sleep(500);
            this.sex = sex;
            System.out.println("生产: " + getName() + " : " + getSex());
            // 将标志为重置
            isEmpty = false;
            condition.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            reentrantLock.unlock();
        }

    }

    // 加synchronized可以解决
    public void get() {
        reentrantLock.lock();
        try {
            // 如果为空的时候
            while (isEmpty) {
                condition.await();
            }
            System.out.println("消费: " + getName() + " : " + getSex());
            isEmpty = true;
            // 唤醒生产者
            condition.signal();
        } catch (Exception e) {
            System.out.println("异常");
        } finally {
            // 释放锁
            reentrantLock.unlock();
        }

    }
}
